package com.fc.advbox.utils;

import com.fc.advbox.utils.xss.SQLFilter;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 查询参数
 *
 * @author Rocky

 * @date 2017-03-14 23:15
 */
public class Query extends LinkedHashMap<String, Object> {
	private static final long serialVersionUID = 1L;

	private static final int DEFAULT_PAGE = 1;

    private static final int DEFAULT_LIMIT = 20;

    private static final int MIN_LIMIT = 1;

	//当前页码
    private int page = DEFAULT_PAGE;
    //每页条数
    private int limit = DEFAULT_LIMIT;

    public Query(Map<String, Object> params){
        if (params != null) {
            this.putAll(params);

            //分页参数
            if(params.containsKey("page")){
                this.page = Integer.parseInt(params.get("page").toString());
            }

            if (this.page < DEFAULT_PAGE) {
                this.page = DEFAULT_PAGE;
            }

            if(params.containsKey("limit")){
                this.limit = Integer.parseInt(params.get("limit").toString());
            }

            if (this.limit < MIN_LIMIT) {
                this.limit = DEFAULT_LIMIT;
            }

            //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
            if(params.containsKey("sidx")){
                String sidx = params.get("sidx").toString();
                this.put("sidx", SQLFilter.sqlInject(sidx));
            }

            if(params.containsKey("order")){
                String order = params.get("order").toString();
                this.put("order", SQLFilter.sqlInject(order));
            }
        }

        this.put("offset", (page - 1) * limit);
        this.put("page", page);
        this.put("limit", limit);
    }


    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }
}
